from flask import Blueprint, request, current_app, jsonify
from werkzeug.utils import secure_filename
import json
import os
import logging
from utils import allowed_file, unique_filename
from modules.image_similarity.service import compute_structural_similarity

# 创建蓝图
image_similarity_blueprint = Blueprint('image_similarity', __name__)
logger = logging.getLogger("image_similarity")


@image_similarity_blueprint.route("/image-similarity/ssim", methods=["POST"])
def structural_similarity_route():
    """
    结构相似度(SSIM)比较API端点

    需要上传两个图像文件:
    - image1: 第一张图像
    - image2: 第二张图像

    可选参数 (作为JSON字符串通过form-data中的'data'字段提供):
    - threshold: 相似度阈值 (0.0-1.0 之间)
    - params: 
        - win_size: 窗口大小
        - sigma: 高斯滤波器标准差
        - alpha: 亮度权重 (0.0-1.0)
        - beta: 对比度权重 (0.0-1.0)
        - gamma: 结构权重 (0.0-1.0)

    返回:
    - structure_score: 结构相似度得分 (0.0-1.0)
    - match: 是否匹配 (基于阈值)
    - diff_image_base64: Base64编码的差异图像
    - diff_map_base64: Base64编码的差异热图
    """
    # 检查是否有文件上传
    if "image1" not in request.files or "image2" not in request.files:
        return {"error": "缺少必要的图像文件"}, 400

    image1_file = request.files["image1"]
    image2_file = request.files["image2"]

    # 验证文件名
    if image1_file.filename == "" or image2_file.filename == "":
        return {"error": "未选择文件"}, 400

    # 验证文件类型
    if not (allowed_file(image1_file.filename, current_app.config["ALLOWED_EXTENSIONS"]) and
            allowed_file(image2_file.filename, current_app.config["ALLOWED_EXTENSIONS"])):
        return {"error": "不支持的文件类型"}, 400

    try:
        # 保存上传的文件
        image1_filename = unique_filename(
            secure_filename(image1_file.filename))
        image1_path = os.path.join(
            current_app.config["UPLOAD_FOLDER"], image1_filename)
        image1_file.save(image1_path)

        image2_filename = unique_filename(
            secure_filename(image2_file.filename))
        image2_path = os.path.join(
            current_app.config["UPLOAD_FOLDER"], image2_filename)
        image2_file.save(image2_path)

        # 解析请求参数
        data = {}
        if 'data' in request.form:
            try:
                data = json.loads(request.form.get("data"))
            except Exception as e:
                logger.warning(f"解析请求数据出错: {str(e)}")

        threshold = data.get("threshold", 0.8)
        params = data.get("params", {})

        # 计算结构相似度
        result, status_code = compute_structural_similarity(
            image1_path,
            image2_path,
            threshold,
            params
        )

        # 删除临时文件
        os.remove(image1_path)
        os.remove(image2_path)

        return jsonify(result), status_code

    except Exception as e:
        logger.exception(f"图像相似度比较出错: {str(e)}")

        # 清理临时文件
        if 'image1_path' in locals() and os.path.exists(image1_path):
            os.remove(image1_path)
        if 'image2_path' in locals() and os.path.exists(image2_path):
            os.remove(image2_path)

        return {"error": f"处理过程中出错: {str(e)}"}, 500
